<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>切换图片的案例</title>
</head>
<style type="text/css">
  * {
    margin: 0;
    padding: 0;
  }

  .container {
    box-sizing: border-box;
    width: 80%;
    height: 521px;
    margin: 20px auto;
    background-color: yellowgreen;
  }

  .container>.text {
    height: 40px;
    width: 80%;
    margin: 0 auto;
    line-height: 40px;
    text-align: center;
  }

  .container>.img {
    width: 90%;
    height: 431px;
    margin: 0 5% 0 5%;
  }

  .container>.prev {
    margin: 0 0 0 45%;
  }
</style>

<body>
  <div class="container">
    <div class="text">第2张图片</div>
    <img class="img" src="../img/mi2.webp" alt="">
    <button class="prev">上一张</button>
    <button class="next">下一张</button>
  </div>
  <script>
    let img = document.querySelector(".img");
    let prev = document.querySelector(".prev");
    let next = document.querySelector(".next");
    let text = document.querySelector(".text");
    let index = 2;
    let interval2;
    //定时驱动：一秒驱动一次
    // (function () {
    let interval1 = setInterval(() => {
        console.log(123);
        index++;
        if (index === 6) {
          index = 2;
        }
        img.src = `../img/mi${index}.webp`;
        text.innerHTML = `第${index}张图片`;
      }, 200);
    // })();

    //鼠标移出来，定时驱动启动
    img.onmouseleave = function () {
      interval2 = setInterval(function () {
        index++;
        if (index === 6) {
          index = 2;
        }
        img.src = `../img/mi${index}.webp`;
        text.innerHTML = `第${index}张图片`;
      }, 1000);
    }
    //鼠标移上去，停止定时驱动
    img.onmouseover = function () {
      clearInterval(interval1);
      clearInterval(interval2);
    }
    //右点击事件
    let rightClick = function () {
      clearInterval(interval1);
      clearInterval(interval2);
      next.addEventListener("click", function () {
        index++;
        if (index === 6) {
          index = 2;
        }
        img.src = `../img/mi${index}.webp`;
        //设置顶部文字
        text.innerHTML = `第${index}张图片`;
      })
    };
    rightClick();

    //左点击事件
    prev.addEventListener("click", function () {
      clearInterval(interval1);
      clearInterval(interval2);
      index--;
      if (index === 1) {
        index = 5;
      }
      img.src = `../img/mi${index}.webp`;
      text.innerHTML = `第${index}张图片`;
    })
  </script>
</body>

</html>